import json

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View

from param.models import Param, ParamSerializer
from resource.models import Resource, ResourceSerializer


# 根据id获取记录
class GetParam(View):
    def get(self, req):
        try:
            param = Param.objects.get(id=int(req.GET['id']))
            return JsonResponse({'code': 200, 'data': ParamSerializer(param).data})
        # 捕获数据库查询异常（如修改时id不存在）
        except Param.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'msg': f'异常：ID为 {req.GET['id']} 的记录不存在!'
            })
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })


# 新增或修改
class SaveView(View):
    def post(self, request):
        try:
            data = json.loads(request.body.decode('utf-8'))
            if data['id'] == -1:  # 添加
                obj = Param(resource=Resource.objects.get(id=data['resource']), X1=data['X1'], X2=data['X2'],
                            N_tr=data['N_tr'], P_tr=data['P_tr'], K_tr=data['K_tr'], M_tr=data['M_tr'],
                            trrz=data['trrz'],
                            N_lm=data['N_lm'], P_lm=data['P_lm'], K_lm=data['K_lm'], B_nian=data['B_nian'],
                            P_s=data['P_s'], E=data['E'], C=data['C'], R_c=data['R_c'], S_tr=data['S_tr'],
                            Q_flz=data['Q_flz'], L=data['L'], Q_SO2=data['Q_SO2'], Q_F=data['Q_F'], Q_NO=data['Q_NO'],
                            Q_TSP=data['Q_TSP'], Q_PM10=data['Q_PM10'], Q_PM25=data['Q_PM25'], n=data['n'],
                            LAI=data['LAI'],
                            A_ffgs=data['A_ffgs'], Y1=data['Y1'], Y2=data['Y2'],
                            remark=data['remark'])
                obj.save()
            else:  # 修改
                obj = Param(id=data['id'],
                            resource=Resource.objects.get(id=data['resource']), X1=data['X1'], X2=data['X2'],
                            N_tr=data['N_tr'], P_tr=data['P_tr'], K_tr=data['K_tr'], M_tr=data['M_tr'],
                            trrz=data['trrz'],
                            N_lm=data['N_lm'], P_lm=data['P_lm'], K_lm=data['K_lm'], B_nian=data['B_nian'],
                            P_s=data['P_s'], E=data['E'], C=data['C'], R_c=data['R_c'], S_tr=data['S_tr'],
                            Q_flz=data['Q_flz'], L=data['L'], Q_SO2=data['Q_SO2'], Q_F=data['Q_F'], Q_NO=data['Q_NO'],
                            Q_TSP=data['Q_TSP'], Q_PM10=data['Q_PM10'], Q_PM25=data['Q_PM25'], n=data['n'],
                            LAI=data['LAI'],
                            A_ffgs=data['A_ffgs'], Y1=data['Y1'], Y2=data['Y2'], remark=data['remark'])
                obj.save()
            return JsonResponse({'code': 200, 'msg': '执行成功！'})
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })


# 信息查询
class SearchView(View):
    def post(self, req):
        try:
            data = json.loads(req.body.decode('utf-8'))

            pageNum = data['pageNum']  # 当前页
            pageSize = data['pageSize']  # 每页大小
            city = data['city']
            county = data['county']
            town = data['town']
            forest_class = data['forestClass']
            ecological_zone = data['ecologicalZone']

            queryset = Param.objects.all().order_by('resource__address__city', 'resource__address__county',
                                                    'resource__ecological_zone',
                                                    'resource__forest_class', 'resource__origin',
                                                    'resource__dominant_tree_species')

            # 先构建基础查询条件（必选条件：city）
            if city:
                queryset = queryset.filter(resource__address__city__in=city)
            if county:  # 如果county列表有元素（非空）
                queryset = queryset.filter(resource__address__county__in=county)
            if town:  # 如果county列表有元素（非空）
                queryset = queryset.filter(resource__address__town__in=town)
            if forest_class:
                queryset = queryset.filter(resource__forest_class__name__in=forest_class)
            if ecological_zone:
                queryset = queryset.filter(resource__ecological_zone__name__in=ecological_zone)

            # 获取查询集
            # queryset = Param.objects.filter(X1__icontains=query)
            # queryset = Param.objects.all()
            total = queryset.count()

            # 分页
            paginator = Paginator(queryset, pageSize)
            dataPage = paginator.page(pageNum)

            # 序列化数据 - 传递查询集给序列化器
            serializer = ParamSerializer(dataPage.object_list, many=True)

            # print('ParamSerializer data:', serializer.data[0])

            return JsonResponse({'code': 200, 'data': serializer.data, 'total': total})
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })


class ActionView(View):
    def get(self, request):
        # 根据id获取用户信息
        id = request.GET.get("id")
        obj = Param.objects.get(id=id)
        return JsonResponse({'code': 200, 'param': ParamSerializer(obj).data})

    def delete(self, request):
        # 删除操作
        try:
            idList = json.loads(request.body.decode("utf-8"))
            Param.objects.filter(id__in=idList).delete()
            return JsonResponse({'code': 200, 'msg': '删除成功！'})
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })


# 查询未录入参数的资源
class ResourceNoParam(View):
    def post(self, req):
        try:
            data = json.loads(req.body.decode('utf-8'))

            pageNum = data['pageNum']  # 当前页
            pageSize = data['pageSize']  # 每页大小
            city = data['city']
            county = data['county']
            town = data['town']
            forest_class = data['forestClass']
            ecological_zone = data['ecologicalZone']

            obj_params = Param.objects.all()
            param_ids = [obj.resource.id for obj in obj_params]

            # 获取查询集
            queryset = Resource.objects.exclude(id__in=param_ids).order_by('address__city', 'address__county',
                                                                           'ecological_zone', 'forest_class', 'origin',
                                                                           'dominant_tree_species')

            # 先构建基础查询条件（必选条件：city）
            if city:
                queryset = queryset.filter(address__city__in=city)
            if county:  # 如果county列表有元素（非空）
                queryset = queryset.filter(address__county__in=county)
            if town:  # 如果county列表有元素（非空）
                queryset = queryset.filter(address__town__in=town)
            if forest_class:
                queryset = queryset.filter(forest_class__name__in=forest_class)
            if ecological_zone:
                queryset = queryset.filter(ecological_zone__name__in=ecological_zone)

            total = queryset.count()
            # 分页
            paginator = Paginator(queryset, pageSize)
            dataPage = paginator.page(pageNum)

            # 序列化数据 - 传递查询集给序列化器
            serializer = ResourceSerializer(dataPage.object_list, many=True)

            return JsonResponse({'code': 200, 'data': serializer.data, 'total': total})
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })
